if (!com) var com = {}
if (!com.logicpartners) com.logicpartners = {}
if (!com.logicpartners.designerTools) com.logicpartners.designerTools = {}

com.logicpartners.designerTools.image = function() {
  var self = this
  this.counter = 1
  this.data = null
  this.width = null
  this.height = null
  this.readonly = ['data']

  this.button = $('<div></div>')
    .addClass('designerToolbarImage designerToolbarButton')
    .attr('title', 'Image')
    .append($('<div></div>'))
  this.activate = function(toolbar) {
    self.data = null

    // Open up a dialog to get the image
    var dialog = $('<div></div>').prop('title', '选择图片(左侧为原图，右侧为打印效果图)')
    var imageFile = $('<input type="file" />')
      .css({ width: 400 })
      .on('change', function() {
        if (typeof window.FileReader !== 'function') {
          alert(
            'This page requires the file API that is included in modern browsers such as Google Chrome. Please try again in an up to date web browser.',
          )
        }
        var input = imageFile[0]
        if (!input.files[0]) {
          alert('Please select a file to insert.')
          // } else if (input.files[0].size > 5 * 1024) {
          //   alert('图片太大了! 请上传5KB内图片')
          //   return
          // } else {
        } else {
          var file = input.files[0]
          self['file'] = file
          var reader = new FileReader()
          var insertImg = imageLeft
          var canvasResult = imageRight
          reader.onloadend = function() {
            var canvas = canvasResult
            var imgSelf = insertImg
            insertImg.css({ width: 'auto', height: 'auto', 'max-width': 200, 'max-height': 200 })
            canvas.css({ width: 'auto', height: 'auto' })
            insertImg[0].onload = function() {
              var tCanvas = $('<canvas />')
              tCanvas[0].width = imgSelf[0].width
              tCanvas[0].height = imgSelf[0].height
              canvas[0].width = imgSelf[0].width
              canvas[0].height = imgSelf[0].height
              var tctx = tCanvas[0].getContext('2d')
              var ctx = canvas[0].getContext('2d')
              tctx.drawImage(imgSelf[0], 0, 0, tCanvas[0].width, tCanvas[0].height)
              var tImgData = tctx.getImageData(0, 0, tCanvas[0].width, tCanvas[0].height)
              var imgData = ctx.getImageData(0, 0, tCanvas[0].width, tCanvas[0].height)

              // Convert the canvas data to GRF.
              for (var y = 0; y < tCanvas[0].height; y++) {
                for (x = 0; x < tCanvas[0].width; x++) {
                  var pixelStart = 4 * (tCanvas[0].width * y + x)
                  var luminance =
                    tImgData.data[pixelStart] * 0.299 +
                    tImgData.data[pixelStart + 1] * 0.587 +
                    tImgData.data[pixelStart + 2] * 0.114

                  if (luminance > 127) {
                    imgData.data[pixelStart] = 255
                    imgData.data[pixelStart + 1] = 255
                    imgData.data[pixelStart + 2] = 255
                    imgData.data[pixelStart + 3] = 255
                  } else {
                    imgData.data[pixelStart] = 0
                    imgData.data[pixelStart + 1] = 0
                    imgData.data[pixelStart + 2] = 0
                    imgData.data[pixelStart + 3] = 255
                  }
                }
              }
              self.width = canvas[0].width
              self.height = canvas[0].height
              self.data = imgData.data
              self.imgData = imgData
              ctx.putImageData(imgData, 0, 0)
              console.log(self.width, 'self.width')
              // 获取的是canvas后的图，黑白色
              self.src = canvas[0].toDataURL('image/png')
            }
            insertImg[0].src = reader.result

            // 获取的是原图

            // self.src = reader.result
          }
          reader.readAsDataURL(file)
        }
      })
      .appendTo(dialog)
    var imageContainer = $('<div></div>').css({ 'padding-top': '5px' })
    var imageLeft = $('<img />')
      .prop('src', './img/blank.gif')
      .prop('title', '原图')
      .prop('border', 'none')
      .css({ float: 'left', width: 200, height: 200, border: '1px solid #DDDDDD' })
      .appendTo(imageContainer)
    var imageRight = $('<canvas />')
      .css({ float: 'right', width: 200, height: 200, border: '1px solid #DDDDDD' })
      .appendTo(imageContainer)

    imageContainer.appendTo(dialog)

    var Toolbar = toolbar
    dialog
      .dialog({
        modal: true,
        width: 470,
        height: 400,
        buttons: {
          Insert: function() {
            // Insert the image onto the screen.
            if (!self.data) {
              alert('请选择图片!')
            } else {
              // self.data
              Toolbar.labelDesigner.addObject(new self.object(0, 0, self.width, self.height, self.src))
              $(this).dialog('close')
            }
          },
          Cancel: function() {
            self.data = null
            $(this).dialog('close')
          },
        },
      })
      .on('dialogclose', { toolbar: toolbar }, function(event) {
        self.button.removeClass('designerToolbarButtonActive')
        event.data.toolbar.setTool(null)
      })
  }

  this.object = function(x, y, width, height, data) {
    let scale = labelData.labelScale || 8
    this.toolName = 'image'
    this.uniqueID = self.counter
    this.name = 'Image ' + self.counter++
    this.x = x
    this.y = y
    this.width = width
    this.height = height
    this.data = data
    this.hidden = ['data', 'uniqueID']
    this.props = {
      type: { label: '类型', default: '图片' },
      name: { label: '元素', default: 'image ' + self.counter++ },
      x: { label: '起始位置x(mm)', default: x },
      y: { label: '起始位置y(mm)', default: y },
      width: { label: '宽度(mm)', default: precisionNumber(self.width / scale) },
      height: { label: '高度(mm)', default: precisionNumber(self.height / scale) },
      ZindexTop: { label: '置顶', button: '置顶' },
      ZindexBottom: { label: '置底', button: '置底' },
      ZindexUp: { label: '上移一层', button: '上移一层' },
      ZindexDown: { label: '下移一层', button: '下移一层' },
    }
    this.readonly = ['type']
    for (var prop in this.props) {
      this[prop] = this.props[prop].default
    }
    ;(this.getZPLData = (function() {
      var GRFVal = function(nibble) {
        var nibbleMap = {
          0: '0000',
          1: '0001',
          2: '0010',
          3: '0011',
          4: '0100',
          5: '0101',
          6: '0110',
          7: '0111',
          8: '1000',
          9: '1001',
          A: '1010',
          B: '1011',
          C: '1100',
          D: '1101',
          E: '1110',
          F: '1111',
        }

        for (key in nibbleMap) {
          if (nibbleMap[key] == nibble) {
            return key
          }
        }

        return ''
      }

      var imgData = ''
      var bytesPerLine = Math.ceil(this.width / 8)
      for (var y = 0; y < this.height; y++) {
        var nibble = ''
        var bytes = 0
        for (var x = 0; x < this.width; x++) {
          var point = 4 * (this.width * y + x)
          if (this.data[point + 1] == 0) {
            nibble += '1'
          } else nibble += '0'

          if (nibble.length > 7) {
            imgData += GRFVal(nibble.substring(0, 4)) + GRFVal(nibble.substring(4, 8))
            nibble = ''
            bytes++
          }
        }

        if (nibble.length > 0) {
          while (nibble.length < 8) nibble += '0'
          imgData += GRFVal(nibble.substring(0, 4)) + GRFVal(nibble.substring(4, 8))
          nibble = ''
          bytes++
        }

        while (bytes < bytesPerLine) {
          imgData += GRFVal('0000') + GRFVal('0000')
          bytes++
        }

        imgData += '\n'
      }

      return '~DGIMG' + this.uniqueID + ',' + bytesPerLine * height + ',' + bytesPerLine + ',' + imgData
    })(
      (this.toZPL = function(labelx, labely, labelwidth, labelheight) {
        return self.imgZpl
      }),
    )),
      (this.draw = function(context, scale) {
        var _this = this
        _this.x = precisionNumber(this.x)
        _this.y = precisionNumber(this.y)
        _this.width = Math.round(_this.width)
        _this.height = Math.round(_this.height)
        // 单色展示： 注意object 传值
        // var ctxData = context.getImageData(x1 * scale, y1 * scale, imgW * scale, imgH * scale)
        // var ctxData = context.getImageData(0, 0, width, height)
        // let imgData2 = new Uint8ClampedArray(Object.values(imgData))
        // this.x = precisionNumber(this.x)
        // this.y = precisionNumber(this.y)
        // if (this.x == 0) {
        //   this.x = 1
        //   this.y = 1
        // }
        // let dataImg = new ImageData(imgData2, imgW * scale, imgH * scale)
        // context.putImageData(dataImg, this.x * scale, this.y * scale)

        var i = new Image()
        i.src = this.data
        if (this.x == 0) {
          this.x = 1
          this.y = 1
        }
        context.drawImage(i, _this.x, _this.y, _this.width, _this.height)

        i.onload = function() {
          context.drawImage(i, _this.x, _this.y, _this.width, _this.height)
        }

        let file = dataURLtoFile(this.data, 'png')
        var formFile = new FormData()
        formFile.append('file', file) //加入文件对象
        getZpl(formFile, _this.width * 8, _this.height * 8).then(r => {
          self.imgZpl = `^FO${this.x},${this.y}  ${r}^XGR:Temp0.GRF,1,1^FS`
        })
      })

    this.setWidth = function(width) {
      if (this.readonly && this.readonly.includes('width')) return
      this.width = precisionNumber(width)
    }

    this.getWidth = function() {
      return this.width
    }

    this.setHeight = function(height) {
      // height = height
      if (this.readonly && this.readonly.includes('height')) return
      this.height = precisionNumber(height)
    }

    this.getHeight = function() {
      return this.height
    }

    this.setHandle = function(coords) {
      this.handle = this.resizeZone(coords)
    }

    this.getHandle = function() {
      return this.handle
    }

    this.drawActive = function(context) {
      context.dashedStroke(
        this.x,
        this.y,
        this.x + this.width,
        this.y + this.height,
        [1, 0.5],
        // parseInt(this.x),
        // parseInt(this.y),
        // parseInt(this.x) + parseInt(this.width),
        // parseInt(this.y) + parseInt(this.height),
        // [1, 0.5],
      )
    }

    this.hitTest = function(coords) {
      return (
        coords.x >= parseInt(this.x) &&
        coords.x <= parseInt(this.x) + parseInt(this.width) &&
        coords.y >= parseInt(this.y) &&
        coords.y <= parseInt(this.y) + parseInt(this.height)
      )
    }
  }
}
function dataURLtoFile(dataurl, filename) {
  //将base64转换为文件
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
function getZpl(formFile, w, h) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: toZpl + '?rwidth=' + w + '&rheight=' + h,
      type: 'post',
      headers: {
        Authorization: `Bearer ${token}`,
      },
      contentType: false,
      processData: false,
      data: formFile,
      success: function(r) {
        return resolve(r.data)
      },
    })
  })
}
